<?php

class AdminProductPostController extends BController
{
	public $defaultAction = 'admin';

	public function filters(){return array('rights');}


	/**
	 * Manages all models.
	 */
	public function actionAdmin($channel_id)
	{
		$model=new ProductPost('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['ProductPost']))
			$model->attributes=$_GET['ProductPost'];

		$criteria = new CDbCriteria;
		$criteria->condition = 'channel_id=:channel_id';
		$criteria->params = array(':channel_id'=>$channel_id);
		$dataProvider = $model->search($criteria);

		$channel = ProductChannel::model()->findByPk((int)$channel_id);
		if($channel===null)
			throw new CHttpException(404,Yii::t('backend',"Danh mục không tồn tại hoặc đã bị xóa."));	

		if(Yii::app()->request->isAjaxRequest) 
			$this->renderPartial('admin',array('model'=>$model,'dataProvider'=>$dataProvider));
		else
			$this->render('admin',array('model'=>$model,'dataProvider'=>$dataProvider, 'channel'=>$channel));
	}


	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to this controller's defaultAction page
	 * or "reload" to update page.
	 */
	public function actionCreate($channel_id)
	{
		$model=new ProductPost;

		if(isset($_POST['ProductPost']))
		{
			$model->attributes=$_POST['ProductPost'];
			$model->channel_id = $channel_id;

			$model->create_time = time();
			$model->update_time = time();
			$uploadedFile = CUploadedFile::getInstance($model,'image_link');
			if($uploadedFile !== NULL)
			{
				$path = NFile::createPath(ProductPost::THUMB_PATH,true);//create folder
				$image_link = uniqid() . '.' . $uploadedFile->getExtensionName();
				$model->image_link = $path.'/'.$image_link;
			}

			if($model->save())
			{
				if($uploadedFile !== NULL)
					$uploadedFile->saveAs($model->image_link);

				Yii::app()->user->setFlash('success',Yii::t('backend','Đã thêm dữ liệu mới.'));
				
				if($_POST['action']=='save')
					$this->redirect(array('.'));
				else if($_POST['action']=='update')
					$this->redirect(array('update','id'=>$model->id));
			}
		}

		$this->render('create',array(
			'model'=>$model,
			'channel_id'=>$channel_id
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to this controller's defaultAction page
	 * or "reload"
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		$old = $this->loadModel($id);

		if(isset($_POST['ProductPost']))
		{
			$model->attributes=$_POST['ProductPost'];
			$model->update_time = time();
			// xử lý upload ảnh
			$path = NFile::createPath(ProductPost::THUMB_PATH,true); 
			$uploadedFile = CUploadedFile::getInstance($model,'image_link');

			if($uploadedFile !== NULL)
			{
				@unlink($old->image_link);
				@unlink($old->thumbS);
				$image_link = uniqid() . '.' . $uploadedFile->getExtensionName();
				$model->image_link = $path.'/'.$image_link;
			}
			else 
				$model->image_link  = $old->image_link;

			if($model->save())
			{
				if($uploadedFile !== NULL)
					$uploadedFile->saveAs($model->image_link);
				
				Yii::app()->user->setFlash('success',Yii::t('backend','Đã cập nhật.'));
				
				if($_POST['action']=='save')
					$this->redirect(array('.'));
				else if($_POST['action']=='update')
					$this->refresh();
			}
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}
	
	/** 
	 * Updates a model's attribute by toggling it's value from 0 to 1 and vice-verse
	 * @param string $attr the attribute name to be toggled
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionToggleAttribute($attr, $id)
	{
		$model = $this->loadModel($id);
		$model->$attr = 1 - $model->$attr;
		$model->update(array($attr));
		echo $model->$attr;
	}
	
	/**
	 * Updates multiple records at once, column name to be updated is "sort"
	 */
	public function actionReOrder()
	{
		if(isset($_POST['multisort']))
		{
			$ids = implode(',', array_keys($_POST['multisort']));
			$sql = sprintf("UPDATE %s SET %s = CASE id ", ProductPost::model()->tableName(), "sort");
			foreach ($_POST['multisort'] as $id => $ordinal) {
				$sql .= sprintf("WHEN %d THEN %d ", $id, $ordinal);
			}
			$sql .= "END WHERE id IN ($ids)";
			$command = Yii::app()->db->createCommand($sql);
			$effected_rows = $command->execute();
			
			echo CJSON::encode(array('result'=>'success','effected_rows'=>$effected_rows));
		}
		else
			echo CJSON::encode(array('result'=>'error','message'=>Yii::t('backend','Yêu cầu không hợp lệ!')));
	}

	/** 
	 * Deletes multiple models
	 */
	public function actionMultiDelete()
	{
		if(isset($_POST['multiselect']))
		{
			$success_ids = array();
			$error_ids = array();

			foreach ($_POST['multiselect'] as $key=>$id)
			{
				try 
				{
					$model = $this->loadModel($id);
					if($model->delete())
					{
						array_push($success_ids, $id);
					}
					else
					{
						array_push($error_ids, $id);
					}
				} 
				catch(Exception $e)
				{
					array_push($error_ids, $id);
				}
			}
			$success_ids = count($success_ids)>0?Yii::t('backend','Thành công: ' . implode(', ', $success_ids)):'';
			$error_ids = count($error_ids)>0?Yii::t('backend','Có lỗi: ' . implode(', ', $error_ids)):'';

			echo CJSON::encode(array('result'=>'success','success_ids'=>$success_ids, 'error_ids'=>$error_ids));
		}
		else
			echo CJSON::encode(array('result'=>'error','message'=>Yii::t('backend','Chưa chọn dữ liệu cần thao tác!'))); 
	}

	/** 
	 * Toggle multiple models
	 */
	public function actionMultiToggle($attr)
	{
		if(isset($_POST['multiselect']))
		{
			$ids = implode(',', array_values($_POST['multiselect']));
			foreach ($_POST['multiselect'] as $key=>$id)
			{
				$sql = sprintf("UPDATE %s SET %s = 1 - %s ", ProductPost::model()->tableName(), $attr, $attr);
			}
			$sql .= "WHERE id IN ($ids)";
			$command = Yii::app()->db->createCommand($sql);
			$effected_rows = $command->execute();
			

			echo CJSON::encode(array('result'=>'success', 'str'=>$sql));
		}
		else
			echo CJSON::encode(array('result'=>'error','message'=>Yii::t('backend','Chưa chọn dữ liệu cần thao tác!')));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		// we only allow deletion via POST request
		if(Yii::app()->request->isPostRequest)
		{
			// if user accidentally hit the button more than one or press browser's back button
			try
			{
				$model = $this->loadModel($id);
				if($model->delete())
				{
					Yii::app()->user->setFlash('success',Yii::t('backend','Đã xóa.'));
					$this->redirect(array($this->defaultAction));
				}
				else
				{
					Yii::app()->user->setFlash('error',Yii::t('backend','Có lỗi trong khi xóa dữ liệu.'));
					$this->redirect(array('update','id'=>$model->id));
				}
			} 
			catch(Exception $e)
			{
				Yii::app()->user->setFlash('error',$e->getMessage());
				$this->redirect(array($this->defaultAction));
			}
			
		}
		else
			throw new CHttpException(400,Yii::t('backend','Yêu cầu không hợp lệ!'));
	}


	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id, $cri=NULL)
	{
		$model=ProductPost::model()->findByPk($id, $cri);
		if($model===null)
			throw new CHttpException(404,Yii::t('backend',"Dữ liệu được yêu cầu không tồn tại hoặc đã bị xóa."));	
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='product-post-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
